import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';

export const ExportService = {
  // 导出为PDF
  async exportToPDF(elementId, filename) {
    const element = document.getElementById(elementId);
    if (!element) {
      throw new Error('找不到要导出的元素');
    }
    
    const canvas = await html2canvas(element, {
      scale: 2,
      useCORS: true,
      logging: false
    });
    
    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF({
      orientation: 'landscape',
      unit: 'mm',
      format: 'a4'
    });
    
    const imgWidth = pdf.internal.pageSize.getWidth();
    const imgHeight = canvas.height * imgWidth / canvas.width;
    
    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
    pdf.save(`${filename}.pdf`);
  },
  
  // 导出为JSON
  exportToJSON(data, filename) {
    const jsonStr = JSON.stringify(data, null, 2);
    this._downloadFile(jsonStr, 'application/json', `${filename}.json`);
  },
  
  // 导出为XML
  exportToXML(data, filename) {
    let xmlStr = '<?xml version="1.0" encoding="UTF-8"?>\n<score>\n';
    
    for (const [key, value] of Object.entries(data)) {
      if (Array.isArray(value)) {
        xmlStr += `  <${key}>\n`;
        value.forEach((item, index) => {
          if (Array.isArray(item)) {
            xmlStr += `    <item index="${index}">${item.join(' ')}</item>\n`;
          } else {
            xmlStr += `    <item>${item}</item>\n`;
          }
        });
        xmlStr += `  </${key}>\n`;
      } else {
        xmlStr += `  <${key}>${value}</${key}>\n`;
      }
    }
    
    xmlStr += '</score>';
    this._downloadFile(xmlStr, 'application/xml', `${filename}.xml`);
  },
  
  // 导出为文本
  exportToText(data, filename) {
    let textStr = `标题: ${data.title}\n`;
    textStr += `作曲: ${data.composer}\n`;
    textStr += `作词: ${data.lyricist}\n`;
    textStr += `调号: 1=${data.keySignature}\n`;
    textStr += `拍号: ${data.timeSignature}\n`;
    textStr += `速度: ♩=${data.tempo}\n\n`;
    
    textStr += '简谱:\n';
    data.bars.forEach((bar, index) => {
      textStr += `第${index + 1}小节: ${bar.join(' ')}\n`;
    });
    
    textStr += '\n歌词:\n';
    data.lyrics.forEach((line, index) => {
      textStr += `第${index + 1}行: ${line}\n`;
    });
    
    this._downloadFile(textStr, 'text/plain', `${filename}.txt`);
  },
  
  // 下载文件的辅助方法
  _downloadFile(content, contentType, filename) {
    const blob = new Blob([content], { type: contentType });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    
    setTimeout(() => {
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }, 0);
  }
};